import React, {Component} from "react";

import './index.css';

export default class Item extends Component {

    state = {
        liStyle: {
            mouseEnter: false,
            backgroundColor: 'white'
        }
    }

    /**
     * 处理鼠标移入移除事件
     * @param flag
     * @returns {(function(): void)|*}
     */
    handleMouse = (flag) => {
        return () => {
            this.setState({mouseEnter: flag});
            if (flag) {
                this.setState({liStyle: {backgroundColor: "#ddd"}})
            } else {
                this.setState({liStyle: {backgroundColor: "white"}})
            }
        }
    }

    /**
     * 处理 勾选、取消勾选事件
     */
    handleCheck = (id) => {
        return (event) => {
            // event.target.checked 复选框是否勾选
            // console.log(event.target.checked, id);
            this.props.updateTodo(id, event.target.checked);
        }
    }

    handleDelete = (id) => {
        //this.props.deleteTodo(id);    
        // 需要加上 window. 
        if (window.confirm('是否确定删除?')) {
            this.props.deleteTodo(id);
        }
    }

    render() {
        const {id, name,done} = this.props;
        const {mouseEnter} = this.state;
        return (
            <li style={this.state.liStyle} onMouseEnter={this.handleMouse(true)} onMouseLeave={this.handleMouse(false)}>
                <label>
                    <input type="checkbox" checked={done} onChange={this.handleCheck(id)} />
                    <span>{name}</span>
                </label>
                <button onClick={() => {this.handleDelete(id)}} className="btn btn-danger" style={{display: mouseEnter? 'block':'none'}}>删除</button>
            </li>
        );
    }
}